Ext.onReady(function() {
	var canNew = true;
	var backBtn = {
		text : '返回',
		xtype : 'button',
		listeners : {
			click : function() {
				location.href = "/wuziMgr/wz_apply";
			}
		}
	};
	var saveBtn = {
		text : '保存',
		xtype : 'button',
		listeners : {
			click : function() {
				var grid = Ext.getCmp("orders");
				var store = grid.getStore();
				var models = store.getRange(0, store.getCount());
				var Orders = [];
				for (var i = 0; i < models.length; i++) {
					Ext.Array.include(Orders, {
								DeviceId : models[i].get("DeviceId"),
								Count : models[i].get("Count"),
								UnitPrice : models[i].get("UnitPrice")
							});
				}
				var jsonData = {
					Id : deviceApply.Id,
					OrderNo : "",
					DepartmentId : Ext.getCmp("Department").getValue(),
					GroupId : Ext.getCmp("Flight").getValue(),
					Desp : Ext.getCmp("Desp").getValue(),
					Time : Ext.Date.format(Ext.getCmp("Time").getValue(),
							"Y-m-d H:i:s"),
					Orders : Orders
				}
				Ext.Ajax.request({
							url : "/device_apply/update",
							type : "POST",
							jsonData : jsonData,
							callback : function(options, success, response) {
								if (success) {
									var result = Ext
											.decode(response.responseText);
									if (result.success) {
										location.href = "/wuziMgr/wz_apply";
									} else {
										Ext.Msg.alert("错误", result.msg);

									}
								}
							}
						})
			}
		}
	};
	var exportBtn = {
		text : '导出',
		xtype : 'button',
		listeners : {
			click : function() {
				window.open('/device_apply/export/'+deviceApply.Id + '?time='+new Date().getTime());
			}
		}
	};
	var toolbar = Ext.create('Ext.toolbar.Toolbar', {
				dock : 'top',
				items : []
			});
	Ext.Ajax.request({
				url : 'privilege/has_privilege',
				params : {
					action : '/device_apply/add'
				},
				async: false,
				callback : function(options, success, response) {
					if (success) {
						try {
							var ar = Ext.decode(response.responseText);
							canNew = ar.data;
						} catch (e) {
							canNew = false;
						}
					} else {
						canNew = false;
					}
					toolbar.add(backBtn);
					if (canNew) {
						toolbar.add(saveBtn);
					}
					toolbar.add(exportBtn);
				}
			});
	var departmentStore = Ext.create('Ext.data.Store', {
				fields : [{
							name : 'Id',
							type : 'int'
						}, 'Name'],
				proxy : {
					type : 'ajax',
					url : '/department/all',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var department = Ext.create('Ext.form.ComboBox', {
				fieldLabel : '申请部门',
				labelWidth : 60,
				editable : false,
				width : 200,
				id : 'Department',
				store : departmentStore,
				queryMode : 'local',
				displayField : 'Name',
				valueField : 'Id',
				value : deviceApply.Department.Id
			});

	var flightStore = Ext.create('Ext.data.Store', {
				fields : ["Id", 'Name'],
				proxy : {
					type : 'ajax',
					url : '/flight/all',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var flight = Ext.create('Ext.form.ComboBox', {
				fieldLabel : '申请班组',
				labelWidth : 60,
				editable : false,
				width : 200,
				id : 'Flight',
				store : flightStore,
				queryMode : 'local',
				displayField : 'Name',
				valueField : 'Id',
				value : deviceApply.Group.Id
			});

	var deviceStore = Ext.create('Ext.data.Store', {
				fields : ['Id', {
							name : "Type",
							type : "object"
						}, "Model"],
				proxy : {
					type : 'ajax',
					url : '/device/distinct',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var device = Ext.create('Ext.form.ComboBox', {
				id : "device",
				labelWidth : 60,
				width : 200,
				fieldLabel : '设备类型',
				store : deviceStore,
				editable : false,
				allowBlank : false,
				queryMode : 'local',
				valueField : 'Id',
				tpl : Ext
						.create(
								'Ext.XTemplate',
								'<tpl for=".">',
								'<div class="x-boundlist-item">{Type.Name}({Model})</div>',
								'</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">',
						'{Type.Name}({Model})', '</tpl>')
			});
	var addPanel1 = Ext.create('Ext.toolbar.Toolbar', {
				dock : 'top',
				border : false,
				items : [department, flight]
			});
	var addPanel2 = Ext.create('Ext.form.Panel', {
				dock : 'top',
				margin : '0 10',
				layout : 'hbox',
				border : false,
				items : [device, {
							xtype : 'numberfield',
							id : "Count",
							margin : '0 5',
							labelWidth : 60,
							allowBlank : false,
							width : 200,
							minValue : 0,
							fieldLabel : '数量'
						}, {
							xtype : 'numberfield',
							id : "UnitPrice",
							margin : '0 5',
							labelWidth : 60,
							allowBlank : false,
							width : 200,
							minValue : 0,
							fieldLabel : '单价'
						}, {
							xtype : "button",
							margin : '0 5',
							text : "加入",
							listeners : {
								click : function() {
									if (!addPanel2.isValid()) {
										return;
									}
									var store = device.getStore();
									var deviceId = device.getValue()
									var record = store.findRecord("Id",
											deviceId);
									var grid = Ext.getCmp("orders");
									var gridStore = grid.getStore();

									var tmp = gridStore.findRecord("DeviceId",
											deviceId);
									if (tmp != null) {
										tmp.set("Count", tmp.get("Count")
														+ Ext.getCmp("Count")
																.getValue());
										tmp.set("UnitPrice", Ext
														.getCmp("UnitPrice")
														.getValue());
										gridStore.commitChanges();
									} else {
										gridStore.add({
													DeviceId : deviceId,
													Name : record.get("Type").Name,
													Model : record.get("Model"),
													Count : Ext.getCmp("Count")
															.getValue(),
													UnitPrice : Ext
															.getCmp("UnitPrice")
															.getValue()
												});
									}
								}
							}
						}]
			});

	var store = Ext.create('Ext.data.Store', {
				fields : ["DeviceId", "Name", "Model", "Count", "UnitPrice"]
			});
	if (!Ext.isEmpty(deviceApply.ApplyOrders)) {
		for (var i = 0; i < deviceApply.ApplyOrders.length; i++) {
			var tmp = deviceApply.ApplyOrders[i];
			store.add({
						DeviceId : tmp.Device.Id,
						Name : tmp.Device.Type.Name,
						Model : tmp.Device.Model,
						Count : tmp.Count,
						UnitPrice : tmp.UnitPrice
					});
		}
	}
	var grid = Ext.create('Ext.grid.Panel', {
				id : "orders",
				minHeight : 100,
				store : store,
				margin : '5 10',
				columns : [{
							text : '序号',
							xtype : 'rownumberer',
							width : 40,
							sortable : false
						}, {
							text : '设备类型',
							flex : 1,
							renderer: function(v, meta, record){
								return record.get('Name') + '(' + record.get('Model') + ')';
							}
						}, {
							text : '数量',
							dataIndex : 'Count'
						}, {
							text : "单价",
							dataIndex : "UnitPrice"
						}, {
							text : '操作',
							xtype : 'actioncolumn',
							width : 50,
							items : [{
										icon : 'view/images/delete.png',
										tooltip : 'Delete',
										handler : function(grid, rowIndex,
												colIndex) {
											grid.getStore().removeAt(rowIndex);
										}
									}]
						}]
			});
	var dockedItems = [];
	if(canNew){
		dockedItems = [toolbar, addPanel1, addPanel2];
	}
	else{
		dockedItems = [toolbar, addPanel1];
	}

	var panel = Ext.create("Ext.panel.Panel", {
				title : '',
				autoScroll : true,
				border : false,
				bodyBorder : false,
				dockedItems: dockedItems,
				items : [grid, {
							xtype : 'label',
							text : '用途说明',
							margin : "0 0 0 10"
						}, {
							xtype : 'textareafield',
							id : "Desp",
							value : deviceApply.Desp,
							width : '90%',
							margin : '5 10',
							grow : true
						}, {
							xtype : 'datefield',
							id : "Time",
							labelWidth : 60,
							width : 250,
							margin : '5 10',
							fieldLabel : '申请时间',
							format : 'Y-m-d H:i:s',
							value : deviceApply.Time
						}]
			});
	Ext.create('Ext.Viewport', {
				layout : 'fit',
				style : 'background:none;background-color:white;',
				items : [panel]
			});
});